<?php

Loader::using("underscore::core::util::RequestBinder");

/**
 * Description of BindingPlugin
 *
 * @author JeyDotC
 * 
 * @export Plugins
 */
class BindingPlugin extends UnderscorePlugin implements BeforeTask {

    //For future configuration capabilities.
    private $getPreffix = "get";

    public function beforeTask($task) {
        $metadata = $this->getModule()->getMetadata();

        if ($metadata->hasByMember($task, "Bind")) {

            $annotation = $metadata->findByMember($task, "Bind");
            $routeString = str_replace("Bind:", "", $annotation);
            $route = array_slice(explode(".", $routeString), 1);

            $objectToBind = $this->resolveProperty($this->getModule(), $route);
            $this->bind($objectToBind);
        }
        return true;
    }

    private function bind(&$object) {
        $binder = new RequestBinder();
        $binder->bind($object);
    }

    private function &resolveProperty($object, array $route) {
        $val = $object;

        foreach ($route as $node) {
            if (method_exists($val, $this->getPreffix . $node)) {
                $val = &$val->{$this->getPreffix . $node}();
            } else {
                throw new Exception("Property $node not found");
            }
        }

        return $val;
    }

}
?>

